package com.aydx.remotevaluezookeeper.config;

import com.alibaba.fastjson.JSON;
import com.aydx.remotevaluezookeeper.annonation.ZkValue;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Configuration;


import java.lang.reflect.Field;

@Configuration
@Slf4j
public class ZookeeperValueBeanPostProcessor implements BeanPostProcessor {

    @Autowired
    private CuratorTemplate curatorTemplate;

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

        log.debug("ZookeeperValueBeanPostProcessor.init {}",beanName);

        Class<?> clazz = bean.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            ZkValue zkValue = field.getAnnotation(ZkValue.class);
            try {
                if (zkValue != null && zkValue.key()!=null && !"".equals(zkValue.key().trim())) {
                    //1、反射方式设置属性值
                    field.setAccessible(true);
                    setFiled(field,bean,zkValue);
                    if(zkValue.isWatch()){
                        //如果需要监控，则增加监控
                        this.curatorTemplate.addWatch(zkValue.key(),new Watcher(){
                            @Override
                            public void process(WatchedEvent watchedEvent) {
                                log.debug("event.process",zkValue.key());
                                //设置字段
                                setFiled(field,bean,zkValue);
                                //增加watcher
                                curatorTemplate.addWatch(zkValue.key(),this);
                            }
                        });
                    }
                }
            } catch (Exception e) {
                log.error("init exception", e);
            }
        }
        return bean;
    }

    private void setFiled(Field field,Object bean,ZkValue zkValue){
        try{
            if(zkValue.clazz()!=null && zkValue.clazz().length>0){
                String vl=curatorTemplate.getValue(zkValue.key(), zkValue.defaultValue());
                if(vl!=null){
                    field.set(bean,JSON.parseObject(vl,zkValue.clazz()[0]));
                    log.info("setFiled.success");
                }
            }else{
                field.set(bean, curatorTemplate.getValue(zkValue.key(), zkValue.defaultValue()));
            }
        }catch (Exception e){
            log.error("zkValue.setFiled.error,{}",zkValue.key(),e);
        }

        
    }
}
